<template>
	<view class="wrapper safe-area">
		<view id="header" class="search-header">
			<menu-header>
				<view class="search-box main-flex">
					<uni-icons type="back" size="30" @click="searchBack"></uni-icons>
					<view
						class="search-box-text main-flex-item main-flex"
						@click="clearSearch"
						v-show="isSearch">
						<view class="search-tag main-flex">
							<uni-icons type="search" size="20" color="#666"></uni-icons>
							<view class="search-tag-list">
								<view class="search-tag-item main-flex">
									<text class="search-tag-item-text">{{searchWords}}</text>
									<uni-icons type="closeempty" size="10" color="#666"></uni-icons>
								</view>
							</view>
						</view>
					</view>
					<view class="search-box-text main-flex-item" v-show="!isSearch">
						<uni-easyinput 
							v-model="searchWords"
							focus
							:inputBorder="false"
							:styles="{
								borderColor: '#e3230e'
							}"
							primaryColor="#ccc"
							@confirm="searchFun"
							@clear="clearSearch"
							:placeholder="wordsPlaceholder || '请输入搜索内容'">
							<template #left>
								<uni-icons type="search" size="20" color="#666"></uni-icons>
							</template>
							<template #right>
								<button class="ty-button search-box-btn" @click="searchFun">搜索</button>
							</template>
						</uni-easyinput>
					</view>
				</view>
			</menu-header>
		</view>
		<view class="container" :style="{paddingTop: `${paddingTop}px`}">
			<!-- 历史搜索 -->
			<view class="tags history" v-show="!isSearch">
				<view class="tags-title main-flex">
					<view class="tags-title-text">搜索历史</view>
					<uni-icons
						@click="clearHistory"
						class="tags-title-icon"
						type="trash"
						size="16"
						color="#666"></uni-icons>
				</view>
				<view class="tags-list main-flex">
					<view class="tags-item" v-for="item in historyList" :key="item" @click="clickHistory(item)">{{item}}</view>
				</view>
			</view>
			<!-- 热词 -->
			<view class="tags hot" v-show="!isSearch">
				<view class="tags-title main-flex">
					<view class="tags-title-text">搜索热词</view>
					<uni-icons
						@click="loopHot"
						class="tags-title-icon"
						type="loop"
						size="16"
						v-if="wordList.length > hotSize"
						color="#666"></uni-icons>
				</view>
				<view class="tags-list main-flex">
					<view class="tags-item" v-for="item in hotList" :key="item" @click="clickHistory(item)">{{item}}</view>
				</view>
			</view>
		
			<view class="main" v-show="isSearch">
				<!-- 商品 -->
				<view class="goods">
					<u-waterfall v-model="productList" columns="3">
						<template v-slot:column="{colList, colIndex}">
							<view class="goods-box" v-for="(item, index) in colList" :key="index">
								<goods-item @chooseGoods="chooseGoods" :goods="item"></goods-item>
							</view>
						</template>
					</u-waterfall>
				</view>
				
				<!--加载-->
				<view
					v-if="isNull"
					class="null main-flex">
					<u-empty text="商品为空" icon="/static/images/null.png"></u-empty>
				</view>
				<view
					v-else
					class="more main-flex">
					<uni-load-more :status="status" />
				</view>
			</view>
		
			<view class="main" v-show="!isSearch">
				<view class="tags">
					<view class="tags-title main-flex">
						<view class="tags-title-text">商品推荐</view>
					</view>
					<view class="goods1">
						<u-scroll-list :indicator="false">
							<view class="goods1-box" v-for="(item, index) in productList" :key="index">
								<goods-item width="300rpx" @chooseGoods="chooseGoods" :goods="item"></goods-item>
							</view>
						</u-scroll-list>
					</view>
				</view>
			</view>
		</view>
			
		
		<!--商品弹窗-->
		<goods-popup
		@close="closeGoods"
		:showGoods="showGoods"
		:goods="goodsInfo"></goods-popup>
	</view>
</template>

<script setup>
import { product } from "@/api/app_api/product"
import { getNode } from '@/utils/ty.js';
import { computed, getCurrentInstance, ref, watch } from 'vue';
import { onReady, onLoad, onReachBottom } from '@dcloudio/uni-app';
import useUserStore from '@/store/modules/user'
import useSetStore from '@/store/modules/set'
import modal from '@/plugins/modal'
	
	const userStore = useUserStore()
	const setStore = useSetStore()
	
	// 页面设置
	const windowHeight = ref(0)
	const pageHeight = ref(0)
	const paddingTop = ref(0)
	const instance = getCurrentInstance()
	const init = async () => {
		// #ifdef MP-WEIXIN
		const height = uni.getWindowInfo().windowHeight
		// #endif
		// #ifndef MP-WEIXIN
		const height = uni.getSystemInfoSync().windowHeight
		// #endif
		const query = uni.createSelectorQuery()
		const node = await getNode(query, '#header')
		paddingTop.value = node?.height || 0
		windowHeight.value = height
		pageHeight.value = height - node.height
	}
	
	// 搜索
	const searchWords = ref('')
	const wordsPlaceholder = ref('')
	const isSearch = ref(false)
	const searchFun = () => {
		if (searchWords.value) {
			isSearch.value = true
			searchFirst()
			setHistory(searchWords.value)
		}
	}
	// 清空搜索
	const clearSearch = () => {
		isSearch.value = false
		searchWords.value = ''
		searchFirst()
	}
	// 搜索返回
	const searchBack = () => {
		if (isSearch.value) {
			clearSearch()
		} else {
			uni.navigateBack({
				delta: 1
			})
		}
	}
	
	// 搜索历史
	const historyList = ref([])
	const historySize = 3
	
	const getHistory = () => {
		historyList.value = uni.getStorageSync('tyWordsHistory') || []
	}
	const setHistory = (word) => {
		if (historyList.value.indexOf(word) === -1) {
			historyList.value.unshift(word)
			saveHistory()
		}
	}
	const saveHistory = () => {
		if (historyList.value.length > historySize) {
			historyList.value = historyList.value.slice(0, historySize)
		}
		uni.setStorageSync('tyWordsHistory', historyList.value)
	}
	const clearHistory = () => {
		historyList.value = []
		uni.removeStorageSync('tyWordsHistory')
	}
	
	// 点击搜索历史
	const clickHistory = (word) => {
		searchWords.value = word
		isSearch.value = true
		searchFirst()
	}
	
	// 热词
	const hotPage = ref(0)
	const hotSize = ref(10)
	const wordList = ref(setStore?.sys?.hot_words || [])
	const hotList = computed(() => {
		let result = []
		if (wordList.value.length > hotSize.value) {
			for (let i = 0; i < hotSize.value; i++) {
				const index = (hotPage.value + i) % wordList.value.length
				if (wordList.value[index]) {
					result.push(wordList.value[index])
				}
			}
		} else {
			result = wordList.value
		}
		return result
	})
	// 更新热词
	const loopHot = () => {
		hotPage.value = (hotPage.value + hotSize.value) % wordList.value.length
	}
	
	// 商品查询
	const productList = ref([])
	const pageNum = ref(1)
	const pageSize = ref(12)
	const total = ref(0)
	const isLoading = ref(false)
	const status = ref('more')
	const isNull = ref(false)
	
	const searchFirst = () => {
		pageNum.value = 1
		productList.value = []
		status.value = 'loading'
		getList()
	}
	
	const getList = () => {
		const params = {
			pageNum: pageNum.value,
			pageSize: pageSize.value,
			sellChannel: userStore.sellChannel,
			regionCode: userStore.regionCode
		}
		if (searchWords.value) {
			params.productName = searchWords.value
		} else {
			params.recommend = 1
			params.pageSize = 6
		}
		isLoading.value = true
		// uni.showLoading({
		// 	title: '数据加载中...'
		// })
		product(params).then(res => {
			productList.value = productList.value.concat(res.data || [])
			status.value = res.data.length === pageSize.value ? 'loading' : 'no-more'
			total.value = res.allNumber
			isNull.value = res.allNumber === 0 && pageNum.value === 1
			isLoading.value = false
			// uni.hideLoading()
		}).catch(() => {
			isLoading.value = false
			// uni.hideLoading()
		})
	}
	
	// 监听
	watch(() => userStore.regionCode, (newVal, oldVal) => {
		searchFirst()
	})
	watch(() => userStore.sellChannel, (newVal, oldVal) => {
		searchFirst()
	})
	watch(() => setStore.sys.hot_words, (newVal, oldVal) => {
		if (newVal) {
			wordList.value = newVal
		}
	}, { deep: true, immediate‌: true })
	
	onReachBottom(() => {
		if(status.value == 'no-more') return false;
		pageNum.value += 1
		status.value = 'loading'
		getList()
	})
	
	// 选择商品
	const showGoods = ref(false)
	const goodsInfo = ref({})
	const chooseGoods = (item) => {
		showGoods.value = true
		goodsInfo.value = item
	}
	const closeGoods = () => {
		showGoods.value = false
		goodsInfo.value = {}
	}
	
	onLoad((option) => {
		if (option.word) {
			wordsPlaceholder.value = option.word
		}
		getHistory()
		searchFirst()
	})
	
	onReady(() => {
		init()
	})
	
	// 微信小程序配置：禁用样式隔离
	defineOptions({
	  options: {
	    styleIsolation: 'shared' // 关键配置
	  }
	})

</script>

<style lang="scss">
	.wrapper {
	}
	.container {
		padding: 0 20rpx;
	}
	.search-header {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		background-color: #ffffff;
		z-index: 10;
		box-sizing: border-box;
		padding: 12rpx 0;
		// #ifdef MP-WEIXIN
		padding-top: 0;
		// #endif
	}
	.search {
		&-box {
			width: 100%;
			height: 100%;
			box-sizing: border-box;
			padding-right: 20rpx;
			:deep(.uni-easyinput) {
				height: 100%;
				.uni-easyinput__content {
					height: 100%;
				}
				.uni-easyinput__content-input {
					height: 100%;
				}
			}
			&-text {
				width: 100%;
				height: 100%;
				background-color: #ffffff;
				border-radius: 200rpx;
				border: 1px solid $primary-color;
				padding: 4rpx 4rpx 4rpx 20rpx;
				box-sizing: border-box;
				overflow: hidden;
			}
			&-btn {
				height: 100%;
				font-size: 24rpx;
				color: #ffffff;
				padding: 0 30rpx;
				margin: 0;
				background-color: $primary-color;
				border-color: $primary-color;
				justify-content: center;
				border-radius: 28rpx;
			}
		}
		&-tag {
			&-list {
				padding: 0 10rpx;
			}
			&-item {
				font-size: 24rpx;
				color: $text-dark;
				padding: 4rpx 10rpx;
				margin: 0;
				background-color: #ccc;
				justify-content: center;
				border-radius: 100rpx;
				&-text {
					margin-right: 10rpx;
				}
			}
		}
	}
	.tags {
		min-height: 100rpx;
		&-title {
			&-text {
				font-size: 28rpx;
				font-weight: 600;
			}
			&-icon {
				margin-left: auto;
			}
		}
		&-list {
			flex-wrap: wrap;
			margin-top: 20rpx;
		}
		&-item {
			font-size: 24rpx;
			padding: 8rpx 16rpx;
			background-color: #ffffff;
			color: $text-light;
			border-radius: 100rpx;
			margin: 0 20rpx 20rpx 0;
		}
	}
	.history {
		margin-top: 20rpx;
	}
	.goods {
		margin-top: 20rpx;
		.goods-box + .goods-box {
			margin-top: 20rpx;
		}
	}
	.goods1 {
		margin: 20rpx 0;
		&-box {
			width: 300rpx;
		}
		.goods1-box + .goods1-box {
			margin-left: 20rpx;
		}
	}
	:deep(.u-column) {
		&:not(:first-child) {
				margin-left: 20rpx !important;
		}
	}
</style>
